package com.lv.controller;


import com.lv.common.AjaxResult;

import com.lv.common.dto.MenuList;
import com.lv.entity.Menu;
import io.swagger.annotations.Api;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * <p>
 *  菜单管理接口
 * </p>
 *
 * @author 凉薄
 * @since 2022-01-06
 */
@RestController
@RequestMapping("/sys/menu")
@Api(tags = "菜单控制")
public class MenuController extends BaseController {
    
    
    @GetMapping("/getMenuList")
    public AjaxResult getMenu(){
        Long id = tokenUntil.getIdByToken(request);
        //获取用户权限
        List<String> userAuthor = userMapper.getUserAuthor(id);
        String[] permissions = userAuthor.toArray(new String[0]);

        //获取用户的菜单
        List<MenuList> menuList = menuService.getMenuListByUserId(id);
        AjaxResult success = AjaxResult.success();
        success.put("permissions",permissions);
        success.put("menuList",menuList);
        return success;
    }

    @GetMapping("/getAllMenu")
    @PreAuthorize("hasAuthority('sys:menu:manager')")
    public AjaxResult getAllMenu(){
        List<Menu> allMenu = menuService.getAllMenu();
        return AjaxResult.success(allMenu);
    }


    @PostMapping("/saveMenu")
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public AjaxResult saveMenu(@RequestBody Menu menu){
        boolean save = menuService.save(menu);
        if(!save){
            return AjaxResult.error("添加失败，请重试！");
        }
        return AjaxResult.success("添加成功");
    }
    @DeleteMapping("/deleteMenu/{id}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public AjaxResult deleteMenu(@PathVariable Long id){
        boolean save = menuService.removeById(id);
        if(!save){
            return AjaxResult.error("删除失败，请重试！");
        }
        userService.clearAuthoritiesInfo(tokenUntil.getIdByToken(request));
        return AjaxResult.success("删除成功");
    }


    @PostMapping("/updateMenu")
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public AjaxResult updateMenu(@RequestBody Menu menu){
        boolean save = menuService.updateById(menu);
        if(!save){
            return AjaxResult.error("编辑失败，请重试！");
        }
        return AjaxResult.success("编辑成功");
    }
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('sys:menu:manager')")
    public AjaxResult getMenuInfoById(@PathVariable Long id){
        Menu menu = menuService.getById(id);
        return AjaxResult.success(menu);
    }
}

